package com.rock.code.bigdata.bigdatainterface.controller;

import com.rock.code.base.controller.BaseController;
import com.rock.code.base.domain.AjaxJson;
import com.rock.code.bigdata.bigdatainterface.domain.Constants;
import com.rock.code.bigdata.bigdatainterface.service.HistoryDataService;
import com.rock.code.bigdata.bigdatainterface.util.MyUtil;
import com.rock.code.common.exceptions.SystemException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CountDownLatch;


/**
 * @author zhouhao
 * @description 历史数据采集    静态属性采集接口
 * @date 2018/9/26 14:28
 * @Version 1.0
 */
@Controller
@RequestMapping("/historyDataColl")
public class HistoryDataCollController extends BaseController {
    private Logger logger = Logger.getLogger(HistoryDataCollController.class);
    @Resource
    private HistoryDataService historyDataService;


    int threadCount = 2;

    final CountDownLatch latch = new CountDownLatch(threadCount);

    /**
     * 采集定义的时间段的历史数据，将数据写入到一个文件中并上传到hdfs上
     *
     * @param startTime
     * @param endTime
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDayCollData", method = RequestMethod.GET)
    public String getDayCollData(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws Exception {


        new Thread(new Runnable() {

            @Override
            public void run() {

                historyDataService.getYesData(Constants.IP_BEIJING, startTime, endTime, "0");

                latch.countDown();
                logger.info("BEIJING 数据采集完成，线程结束");
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {

                historyDataService.getYesData(Constants.IP_TIANJIN, startTime, endTime, "0");

                latch.countDown();
                logger.info("TIANJIN  数据采集完成，线程结束");
            }
        }).start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //执行文件上传
        String fileClass = "collHisdataDuring";
        String date = MyUtil.stampToDate(startTime);
        String year = date.split(" ")[0].split("-")[0];
        String timeDay = date.split(" ")[0].replaceAll("-", "");
        MyUtil.putFileToHdfs(fileClass, year, timeDay);
        this.request.setAttribute("msg", "线程采集开启成功, 请刷新同步记录表查看采集结果。");
        return "bigdata/bigdatainterface/interfaceresult";
    }


    /**
     * 采集历史数据接口   按天采集
     *
     * @param ip        输入监控的ip地址
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{ip}/getHisData", method = RequestMethod.GET)
    public String getHisData(@PathVariable("ip") String ip, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws Exception {


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String time = null;
                    String end = null;
                    time = startTime;
                    end = Long.parseLong(time) + (24 * 60 * 60 * 1000) + "";
                    while (Long.parseLong(time) < Long.parseLong(endTime)) {
                        historyDataService.getHisDataByThread(ip, time, end, "0");
                        try {
                            Thread.sleep(60000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        time = Long.parseLong(time) + (24 * 60 * 60 * 1000) + "";
                        end = Long.parseLong(end) + (24 * 60 * 60 * 1000) + "";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        this.request.setAttribute("msg", "线程采集开启成功, 请刷新同步记录表查看采集结果。");
        return "bigdata/bigdatainterface/interfaceresult";
    }


    /**
     * 按月采集数据
     *
     * @param ip
     * @param startTime 开始时间如：2018-01-01
     * @param endTime   结束时间如：2019-01-01
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{ip}/getHisDataForMonth", method = RequestMethod.GET)
    public String getHisDataForMonth(@PathVariable("ip") String ip, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws Exception {


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String time = null;
                    String end = null;
                    String timeStamp = null;
                    String endStamp = null;
                    time = startTime + " " + "00:00:00";
                    timeStamp = MyUtil.timeToTimeStamp(time);
                    end = MyUtil.addMonth(time, 1);
                    endStamp = MyUtil.timeToTimeStamp(end);
                    while (MyUtil.compare_date(time, endTime) == -1 || MyUtil.compare_date(time, endTime) == 0) {
                        historyDataService.getHisDataByThread(ip, timeStamp, endStamp, "1");
                        try {
                            Thread.sleep(60000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        time = MyUtil.addMonth(time, 1);
                        timeStamp = MyUtil.timeToTimeStamp(time);
                        end = MyUtil.addMonth(end, 1);
                        endStamp = MyUtil.timeToTimeStamp(end);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        this.request.setAttribute("msg", "线程采集开启成功, 请刷新同步记录表查看采集结果。");
        return "bigdata/bigdatainterface/interfaceresult";
    }


    /**
     * 采集历史数据接口   按定义的时间采集
     *
     * @param ip        输入监控的ip地址
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{ip}/getHisDataByTime", method = RequestMethod.GET)
    public String getHisDataByTime(@PathVariable("ip") String ip, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws Exception {


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    historyDataService.getHisDataByThread(ip, startTime, endTime, "1");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
        thread.start();

        this.request.setAttribute("msg", "线程采集开启成功, 请刷新同步记录表查看采集结果。");
        return "bigdata/bigdatainterface/interfaceresult";
    }


    /**
     * 按定义的时间采集  天津数据量每月超过100g，将每月分为3次采集
     *
     * @param ip        输入监控的ip地址
     * @param startTime 开始时间 如2018-01-01
     * @param endTime   结束时间  如  2018-01-10
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{ip}/getHisDataByTimes", method = RequestMethod.GET)
    public String getHisDataByTimes(@PathVariable("ip") String ip, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws Exception {


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String time = null;
                    String end = null;
                    String timeStamp = null;
                    String endStamp = null;
                    time = startTime;
                    timeStamp = MyUtil.timeToTimeStamp(time);
                    end = MyUtil.getEndDate(startTime);
                    System.out.println(end);
                    endStamp = MyUtil.timeToTimeStamp(end);
                    do {
                        System.out.println("执行业务方法start===" + time + "end====" + end);
                        historyDataService.getHisDataByThread(ip, timeStamp, endStamp, "1");
                        int month1 = Integer.parseInt(time.split(" ")[0].split("-")[1]);
                        int year1 = Integer.parseInt(time.split(" ")[0].split("-")[0]);
                        int day1 = Integer.parseInt(time.split(" ")[0].split("-")[2]);

                        if (day1 == 21) {
                            time = MyUtil.getDateLastDay(year1, month1) + " " + "23:59:59";
                        } else {
                            time = MyUtil.getEndDate(time);
                        }
                        timeStamp = MyUtil.timeToTimeStamp(time);
                        int month2 = Integer.parseInt(end.split(" ")[0].split("-")[1]);
                        int year2 = Integer.parseInt(end.split(" ")[0].split("-")[0]);
                        int day2 = Integer.parseInt(end.split(" ")[0].split("-")[2]);
                        if (day2 == 21) {
                            end = MyUtil.getDateLastDay(year2, month2) + " " + "23:59:59";
                        } else {
                            end = MyUtil.getEndDate(end);
                        }
                        endStamp = MyUtil.timeToTimeStamp(end);
                    } while (time.compareTo(endTime) < 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        this.request.setAttribute("msg", "线程采集开启成功, 请刷新同步记录表查看采集结果。");
        return "bigdata/bigdatainterface/interfaceresult";
    }


    /**
     * 将主机静态属性信息存入到静态属性表中
     *
     * @param ip      监控ip地址
     * @param cascade 是否采集子对象数据  true 表示是  false  表示否
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "{ip}/saveStaticType", method = RequestMethod.GET)
    public String saveStaticType(@PathVariable("ip") String ip, @RequestParam(value = "cascade") String cascade) throws Exception {
        if ("".equals(ip) || ip == null) {
            return "请输入北塔监控的ip地址";
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    historyDataService.getStaticByThread(ip, cascade);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        this.request.setAttribute("msg", "线程采集开启成功, 请刷新同步记录表查看采集结果。");
        return "bigdata/bigdatainterface/interfaceresult";


    }


    @ResponseBody
    @RequestMapping(value = "/querySqlResultBySql", method = RequestMethod.POST)
    public AjaxJson querySqlResultBySql() throws Exception {
        Map<String, Object> param = this.getRequestMapSingle();
        List<HashMap> resultMap = null;
        try {
            resultMap = historyDataService.querySqlResultBySql(param);
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("sql 执行错误");
            e.printStackTrace();
            throw new SystemException(e);
        }
        ajaxJson.setSuccess(true);
        ajaxJson.setResult(resultMap);
        return ajaxJson;
    }


}
